package com.fire.market.interceptor;

import com.fire.component.dto.Response;
import com.fire.component.extension.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import java.io.PrintWriter;
import java.io.StringWriter;


@ControllerAdvice(
        //指定拦截包的控制器
        basePackages = {"com.fire.market.controller.*", "com.fire.market.interceptor.*"},
        //限定被标注为@Controller,@RestController的类才拦截
        annotations = {Controller.class, RestController.class}
    )
@Slf4j
public class ControllerExceptionAdvice {
    Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionAdvice.class);

    @ExceptionHandler(value = {BizException.class, OssException.class, SysException.class})
    @ResponseBody
    public Response exception(BaseException ex){
        LOGGER.error("ERROR:" + ex.getErrCode() + ":" + ex.getMessage() +":"+ ex.getCause());
        return Response.buildFailure(ex.getErrCode(), ex.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response defaultException(Exception ex){
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOGGER.error("ERROR:" + sw);
        return Response.buildFailure(BizCommonError.UNKNOWN_ERROR.getErrCode(), BizCommonError.UNKNOWN_ERROR.getErrMsg());
    }
}
